package com.basics.framework.interceptor.impl;


import com.alibaba.fastjson.JSONObject;
import com.basics.common.filter.RepeatedlyRequestWrapper;
import com.basics.common.utils.StringUtils;
import com.basics.common.utils.http.HttpHelper;
import com.basics.framework.interceptor.RepeatSubmitInterceptor;
import com.basics.framework.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {
    public final String REPEAT_PARAMS = "repeatParams";
    public final String REPEAT_TIME = "repeatTime";
    public final String CACHE_REPEAT_KEY = "repeatData";
    @Autowired
    private RedisCache redisCache;
    private int intervalTime = 10;

    public SameUrlDataInterceptor() {
    }

    public void setIntervalTime(int intervalTime) {
        this.intervalTime = intervalTime;
    }

    public boolean isRepeatSubmit(HttpServletRequest request) {
        RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper)request;
        String nowParams = HttpHelper.getBodyString(repeatedlyRequest);
        if (StringUtils.isEmpty(nowParams)) {
            nowParams = JSONObject.toJSONString(request.getParameterMap());
        }

        Map<String, Object> nowDataMap = new HashMap();
        nowDataMap.put("repeatParams", nowParams);
        nowDataMap.put("repeatTime", System.currentTimeMillis());
        String url = request.getRequestURI();
        Object sessionObj = this.redisCache.getCacheObject("repeatData");
        if (sessionObj != null) {
            Map<String, Object> sessionMap = (Map)sessionObj;
            if (sessionMap.containsKey(url)) {
                Map<String, Object> preDataMap = (Map)sessionMap.get(url);
                if (this.compareParams(nowDataMap, preDataMap) && this.compareTime(nowDataMap, preDataMap)) {
                    return true;
                }
            }
        }

        Map<String, Object> cacheMap = new HashMap();
        cacheMap.put(url, nowDataMap);
        this.redisCache.setCacheObject("repeatData", cacheMap, this.intervalTime, TimeUnit.SECONDS);
        return false;
    }

    private boolean compareParams(Map<String, Object> nowMap, Map<String, Object> preMap) {
        String nowParams = (String)nowMap.get("repeatParams");
        String preParams = (String)preMap.get("repeatParams");
        return nowParams.equals(preParams);
    }

    private boolean compareTime(Map<String, Object> nowMap, Map<String, Object> preMap) {
        long time1 = (Long)nowMap.get("repeatTime");
        long time2 = (Long)preMap.get("repeatTime");
        return time1 - time2 < (long)(this.intervalTime * 1000);
    }
}
